﻿using Microsoft.VisualStudio.TestTools.UITesting;
using Microsoft.VisualStudio.TestTools.UITesting.WinControls;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Native;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Automation;

namespace cuicode
{
    [CodedUITest]
    public class cuicode
    {
        [TestMethod]
        public void TestMethod1()
        {
            ApplicationUnderTest app;
            app = ApplicationUnderTest.Launch(@"c:\windows\system32\notepad.exe");

            WinWindow w = UITestControlFactory.FromWindowHandle(app.WindowHandle) as WinWindow;
            foreach (var c in w.GetChildren())
            {
                Console.WriteLine("Name: {0}, Caption: {1}, ControlType: {2}", c.Name, c.FriendlyName, c.ControlType);
                if (c.ControlType.ToString().Equals("Client"))
                {
                    foreach (var c1 in c.GetChildren())
                    {
                        Console.WriteLine("ClassName : {0}", c1.ClassName);
                        if (c1.ClassName.Equals("Edit"))
                        {
                            WinEdit e1 = new WinEdit(c1);
                            e1.Text = "Hello world " + DateTime.Now.ToString();
                        }
                    }

                }
            }
            Console.WriteLine(new string('=', 75));
            app.Process.CloseMainWindow();

            int ret = 0;
            IntPtr hwnd;
            StringBuilder classname = new StringBuilder(100);
            const string DLG_CLASS = "#32770";
            while (true)
            {
                hwnd = Native.User32.GetForegroundWindow();
                ret = Native.User32.GetClassName(hwnd, classname, classname.Capacity);
                Console.WriteLine("Classname : {0} - {1}", classname,DateTime.Now.ToString());
                if (classname.ToString().Equals(DLG_CLASS))
                    break;
                else
                    Playback.Wait(500);
            }
            
            WinWindow d = UITestControlFactory.FromWindowHandle(hwnd) as WinWindow;
            AutomationElement dlg = AutomationElement.FromHandle(hwnd);
            TreeWalker walker = TreeWalker.ContentViewWalker;
            var item = walker.GetFirstChild(dlg);
            Action<AutomationElement> traverse = null;
            StringBuilder name = new StringBuilder();
            traverse = (ae) => { name.AppendLine(ae.Current.Name); ae = walker.GetNextSibling(ae); if(ae != null) traverse(ae); };
            traverse(item);
            app.Dispose();
            Console.WriteLine(new string('=', 75));
            Console.WriteLine("String : {0} ",name);
            Console.WriteLine(new string('=', 75));
        }
    }
}
